<template>
  <div style="font-size:1rem">


    <div class="pay_top">
      <p>请在{{minutes}}分{{seconds}}秒内完成支付功能，超时自动取消</p>
    </div>
    <div v-if="je_sf > 0" class="pay_money">
      <p>{{prescribeInfo.durgstorename}}</p>
      <p>￥{{je_sf}}</p> <!-- je_sf -->  <!-- {prescribeInfo.PRESCRIPTION_PRICE -->
      <p>待付款</p>
    </div>
    <div v-else class="pay_money">
      <p style="line-height: 3rem;letter-spacing: 2px;font-weight: 300;font-size: 1.5rem;">无须支付</p>
    </div>


    <div class="pay_con_details">
      <p>处方费：<span>{{prescribeInfo.cff}}&nbsp;元</span></p>
      <p v-show="showYbInfo">医保支付：<span>{{prescribeInfo.ybzf}}&nbsp;元</span></p>
      <p v-show="showYbInfo">账户支付：<span>{{prescribeInfo.zhzf}}&nbsp;元</span></p>
      <p>现金支付：<span>{{prescribeInfo.xjzf}}&nbsp;元</span></p>
    </div>


    <div class="pay_con_details_jgps">
      <p>煎药费：<span>{{prescribeInfo.jgf || 0}}&nbsp;元</span></p>
      <p>配送费：<span>{{prescribeInfo.psf || 0}}&nbsp;元</span></p>
    </div>


    <div class="pay_bot_div">
      <button v-if="je_sf > 0" @click="perPay" class="pay_bot">立即付款</button>
      <button v-else @click="perPay" class="pay_bot">确  认</button>
    </div>


  </div>
</template>

<script>
import alertTip from '~/components/common/alertTip';
import com_addrVue from './components/com_addr.vue';

const { config } = window;

const wx = require('weixin-js-sdk');

export default {
  data() {
    return {

      showYbInfo: config.YBMODE,

      ts: this.newStore(),
      tq: this.getData(),

      headTitle: '支付方式',

      minutes: 15,
      seconds: 0,

      je_yh: 0, // 优惠金额
      je_sf: 0, // 实际支付的金额

      prescribeInfo:{},
      prescribeInfoDetail:{},

    };
  },

  components: {
    alertTip,
  },
  methods: {
    //
    closeTip() {
      this.showAlert = false;
    },
    //
    perPay() {
      
      const DATA = {
        oid: this.prescribeInfo.ORDERID,
        sid: config.hosInfo.SID,     // 公众号SID
        sfktype: 'orderPay', // 目前只有orderPay，后续功能会有问诊费等等  registerPay  patAsk  qzjPay  docTx
        fkclient: 'wxpay', // 目前只有微信支付
        ayid: '', // 药店ID
        oaid: '', //收货地址ID
        servname: '患者支付处方订单',

        // 服务标志
        fpzt: '', // 是否开发票
        jyfw: '', // 是否需要煎药服务，只有中药类别需要显示此项
        kdfw: '', // 是否需要快递服务

        je_prescribe: this.prescribeInfo.PRESCRIPTION_PRICE, // 药方费（药方*数量）
        je_ybzf: '',
        je_xjzf: '',
        je_jyfw: `${this.prescribeInfo.jgf}`, // 煎药服务费+
        je_kdfw: `${this.prescribeInfo.psf}`, // 快递服务费+
        je_yh: '0', // 优惠金额
        je_ze: this.je_sf, // 需要支付的总金额所有+
        //je_sf: `${this.prescribeInfo.PRESCRIPTION_PRICE+this.prescribeInfo.jgf+this.prescribeInfo.psf-this.je_yh}`, // 实付金额（减掉优惠金额）
        je_sf: this.je_sf,
      };
      this.tq.perPay(DATA,this).then((ts) => {
        const resData = ts.d.DATAOBJ.DATA;

        if (ts.d.RESULT != 200) {  // resData.errCode
          this.$messagebox(ts.d.RESULTTEXT); // resData.errMessage
          return;
        }

        // 调用支付流程
        if (this.je_sf > 0) {
          this.prepayid = resData.extReturn;
          this.PayMoney();
        } else { 
          // this.$router.push({ name: 'chufang-payOff', query: { prescribeInfo: JSON.stringify(this.prescribeInfo), je_sf: this.je_sf, payResult: true, payMessage: '支付成功' } });
          this.$router.push({ name: 'chufang-prescribeRecord'});
        }

      });
    },
    onBridgeReady() {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
          timeStamp: `${this.prepayid.timeStamp}`, // 时间戳，自1970年以来的秒数
          appId: `${this.prepayid.appId}`, // 公众号名称，由商户传入
          nonceStr: `${this.prepayid.nonceStr}`, // 随机串
          package: `${this.prepayid.package}`, //
          signType: `${this.prepayid.signType}`, // 微信签名方式
          paySign: `${this.prepayid.paySign}`, // 微信签名
        },
        (res) => {
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            this.$router.push({ name: 'chufang-payOff', query: { prescribeInfo: JSON.stringify(this.prescribeInfo), je_sf: this.je_sf, payResult: true, payMessage: '支付成功' } });
          } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            this.$messagebox('已取消支付');
          } else {
            this.$messagebox('支付失败', `错误信息: ${res.err_msg}`);
          }
        },
      );
    },
    // 立即支付调用微信接口，生产环境使用
    PayMoney() {
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
        }
      } else {
        this.onBridgeReady();
      }
    },
    changePay() {
      this.payWay = !this.payWay;
    },
    timer() {
      const _this = this;
      const time = window.setInterval(() => {
        if (_this.seconds === 0 && _this.minutes !== 0) {
          _this.seconds = 59;
          _this.minutes -= 1;
        } else if (_this.minutes === 0 && _this.seconds === 0) {
          _this.seconds = 0;
          window.clearInterval(time);
          this.$router.back(-1);
        } else {
          _this.seconds -= 1;
        }
      }, 1000);
    },
    getWxConfigParam() {
      const req = JSON.stringify({
        OTRequest: {
          VERSION: '1.0',
          TN: 'F27.APP.00.09',
          CLIENTID: 'YLAPP',
          RYBID: '',
          TOKEN: '',
          DATA: {
            url: `${encodeURIComponent(`${window.location.href.split('#')[0]}`)}`,
          },
        },
      });
      this.spost(this.ts, '/doctor/AppMainServlet.ap', {
        '': req,
      }).then((ts) => {
        sessionStorage.setItem('appId', ts.d.DATAOBJ.DATA.appId);
        sessionStorage.setItem('timestamp', ts.d.DATAOBJ.DATA.timestamp);
        sessionStorage.setItem('nonceStr', ts.d.DATAOBJ.DATA.nonceStr);
        sessionStorage.setItem('signature', ts.d.DATAOBJ.DATA.signature);
        // alert(`是否成功返回四个参数从本页中获取的 appId:${this.appId}   timestamp:${this.timestamp}   nonceStr:${this.nonceStr}   signature:${this.signature}`);
        // 登录成功后， 初始化扫描参数
        this.wxConfig();
      }).catch();
    },
    wxConfig() {
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: sessionStorage.getItem('appId'), // 必填，公众号的唯一标识
        timestamp: sessionStorage.getItem('timestamp'), // 必填，生成签名的时间戳
        nonceStr: sessionStorage.getItem('nonceStr'), // 必填，生成签名的随机串
        signature: sessionStorage.getItem('signature'), // 必填，签名，见附录1
        jsApiList: [
          'getBrandIAPPayRequest',
          'getCanIAPPay',
          'getBrandWCPayRequest',
          'checkJsApi',
          'chooseImage', // 从本地的相册、图库选择图片
          'previewImage',
          'uploadImage',
          'downloadImage',
          'getNetworkType', // 网络状态接口
          'openLocation', // 使用微信内置地图查看地理位置接口
          'getLocation', // 获取地理位置接口
          'hideOptionMenu', // 界面操作接口1
          'showOptionMenu', // 界面操作接口2
          'closeWindow', // //界面操作接口3
          'hideMenuItems', // //界面操作接口4
          'showMenuItems', // //界面操作接口5
          'hideAllNonBaseMenuItem', // //界面操作接口6
          'showAllNonBaseMenuItem', // //界面操作接口7
          'scanQRCode', // 微信扫一扫接口
        ], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });

      // 判断当前客户端版本是否支持指定JS接口
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ['scanQRCode'], // 需要检测的JS接口列表，
          success(res) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            /*
            alert(res.errMsg);
            if (res.checkResult.scanQRCode) {
              alert('支持扫码接口');
            } else {
              alert('不支持扫码接口');
            }
            */
          },
          error(res) {
            // alert(`初始化扫码信息失败： ${res.errMsg}`);
            console.log(`初始化扫码信息失败： ${res.errMsg}`);
          },
        });
      });

      wx.error((res) => {
        // alert(`出错了：${res.errMsg}`);
        console.log(`出错了：${res.errMsg}`);
      });
    },
    getOrderPayinfo(orderid) {
      console.log("PPPPPPPPPPPP=================" + orderid);

      const DATA = {
        ORDERID: orderid,
      };

      this.tq.getPayOrderInfo(DATA, this).then((ts) => {
      console.log("EEEEEEEEEEEEEEEEEEEEE=================" + JSON.stringify(ts));

      const tempPayInfo = ts.d.DATAOBJ.DATA;

      tempPayInfo.orderDetail.forEach(element => {

        /*         
        if (element.OM_CHARGE_TYPE == 'cf') {
          this.prescribeInfo.cff = element.OM_CHARGE_JE;
        } */
        if (element.OM_CHARGE_TYPE == 'jy') {
          this.prescribeInfo.jgf = element.OM_CHARGE_JE;
        }
        if (element.OM_CHARGE_TYPE == 'ps') {
          this.prescribeInfo.psf = element.OM_CHARGE_JE;
        }

      });

      this.prescribeInfo.zhzf = tempPayInfo.zhzf;
      this.prescribeInfo.ybzf = tempPayInfo.ybzf;
      this.prescribeInfo.xjzf = tempPayInfo.xjzf;
      this.prescribeInfo.cff = tempPayInfo.prescription_price;

      this.je_sf = tempPayInfo.dfkje;

      });

    },

  },
  created() {
    document.title = '处方支付中';
    this.$root.showfooter = false;
    this.hospitalName = sessionStorage.getItem('hosName');
  },
  destroyed() {
    this.$root.showfooter = true;
  },
  mounted() {
    // this.getWxConfigParam();
    console.log("pay.vue ====" + this.$route.query.preinfostr);
    this.timer();
    this.prescribeInfo=JSON.parse(this.$route.query.preinfostr);
    this.getOrderPayinfo(this.prescribeInfo.ORDERID);
  },
  computed: {
    second() {
      return this.num(this.seconds);
    },
    minute() {
      return this.num(this.minutes);
    },
  },
};
</script>

<style scoped>
body {
  /* background: #f1f1f1; */
}
.pay_option {
  display: flex;
  flex-flow: row;
  justify-content: space-between;
  align-items: center;
}
.pay_option span{
  display: flex;
  flex-flow: row;
  justify-content: flex-start;
  align-items: center;
}
.pay_option span:first-child span:first-child{
  margin-right: .2rem;
}
.pay_money {
  text-align: center;
}
.pay_money p{
  background: #fff;
  display: flex;
  flex-flow: column | nowrap;
  justify-content: center;
  padding-top: 1rem;
}
.pay_money p:nth-child(2){
  font-size: 3rem;
  color: #000;
}
.pay_money p:nth-child(3){
  font-size: 1rem;
}
.pay_top {
  /* margin-top: 3rem; */
  background: #ffebcd;
}
.pay_top p {
  color: #bbb;
  line-height: 3rem;
  text-align: center;
  font-size: 0.9rem;
}
.pay_con_details span {
  float: right;
  color: rgb(0, 200, 0);
  background: #fff;
}
.pay_con_details p {
  background: #fff;
  color: #666;
  padding: 0rem 0.6rem;
  margin-bottom: 0;
  line-height: 2.5rem;
  border-bottom: 1px solid #f1f1f1;
  font-family: "Microsoft Yahei";
}
.pay_con_details p:nth-child(2),p:nth-child(3) {
  font-size: .8rem;
}
.pay_con_details p:nth-child(2) span,p:nth-child(3) span{
  color: #666;
}
.pay_con_details_jgps {
  margin-top: 1rem;
}
.pay_con_details_jgps span {
  float: right;
  color: rgb(0, 200, 0);
  background: #fff;
}
.pay_con_details_jgps p {
  background: #fff;
  color: #666;
  padding: 0rem 0.6rem;
  margin-bottom: 0;
  line-height: 2.5rem;
  border-bottom: 1px solid #f1f1f1;
  font-family: "Microsoft Yahei";
}
.pay_con p {
  background: #fff;
  color: #666;
  padding: 0rem 0.6rem;
  margin-bottom: 0;
  line-height: 2.5rem;
  border-bottom: 1px solid #f1f1f1;
  font-family: "Microsoft Yahei";
}
.pay_way {
  margin-top: 1rem;
  margin-bottom: 0;
  line-height: 2rem;
  color: #999;
  font-family: "Microsoft Yahei";
  padding: 0 0 0 .5rem;
  font-size: .8rem;
}
.pay_con .iconfont {
  font-size: 1.6rem;
  padding: 0 0.2rem;
}
.icon-weixinzhifu {
  color: rgb(0, 200, 0);
}
.icon-ziyuan {
  color: rgb(0, 158, 242);
}
.icon-selected {
  float: right;
}
.pay_bot_div {
  width: 100%;
  text-align: center;
  position: fixed;
  bottom: 1rem;
}
.pay_bot {
  margin: 0 auto;
  width: 95%;
  text-align: center;
  line-height: 2.5rem;
  border-radius: 5px;
  /* margin-top: 0.8rem; */
  color: #fff;
  background: #3190e8;
  letter-spacing: 1px;
/*   border: none;
  outline: none;
  bottom:0.4rem; */
}
.pay_bot_back {
  margin: 0 auto;
  width: 95%;
  text-align: center;
  line-height: 2.5rem;
  border-radius: 5px;
  /* margin-top: 0.8rem; */
  color: #fff;
  background: #ccc;
  letter-spacing: 1px;
/*   border: none;
  outline: none;
  bottom:0.4rem; */
}
</style>
